import Vue from "vue";
import Router from "vue-router";

import store from "../store";
import routes from "./routes";

Vue.use(Router);

const router = new Router({
  mode: "history",
  //base: '/sub-path/',
  routes: routes
});

 
 

// router.beforeEach((to, from, next) => {
//   console.log(to);
//   let authrequired = false;
//   if (to && to.meta && to.meta.requiresAuth) authrequired = true;

//console.log("authrequired", authrequired, to.name, from.name);

// if (authrequired) {
//   if (auth.loggedIn()) {
//     if (to.name === "login") {
//       window.location.href = "/";
//       return false;
//     } else {
//       next();
//     }
//   } else {
//     if (to.name !== "login") {
//       window.location.href = "/login";
//       return false;
//     }
//     next();
//   }
// } else {
//   if (auth.loggedIn() && to.name === "login") {
//     window.location.href = "/";
//     return false;
//   } else {
//     next();
//   }
// }

router.beforeEach((to, from, next) => {
  if (to.path === "/logout") {
    store.commit("setLogout");
    next({ path: "/login" });
  } else {
    if (to.matched.some(route => route.meta.requiresAuth)) {
      if (!store.getters.isAuthenticated) {
        console.log("1");
        next({ path: from.path, query: { redirect: to.path } });

      } else {
     
        if (to.matched.some(route => route.meta.roles && store.getters.isInRole(route.meta.roles))) {
          console.log("2");
          next();
        } else if (!to.matched.some(route => route.meta.roles)) {
          console.log("3");
          next({path: "/access-deny"});
        } else {
          console.log("4");
          next({ path: "/" });
        }
      }
    } else {
      if (to.matched.some(route => route.meta.roles && (!store.getters.isAuthenticated || store.getters.isInRole(route.meta.roles)))) {
        console.log("5");
        next();
      } else {
        if (to.matched.some(route => route.meta.roles)) {
          console.log("6");
          next({ path: "/" });
        }
       
        next();
      }
    }
  }
  if (to && to.meta && to.meta.layout) {
    store.commit("setLayout", to.meta.layout);
  }
});

router.afterEach((to, from) => {
  setTimeout(() => {
    store.commit("setSplashScreen", false);
  }, 500);
});

export default router;
